import config from '@/config/wechat'

export const agentUtils = {
	checkPlatform() {
		const ua = navigator.userAgent.toLowerCase();
		if (ua.indexOf('micromessenger') !== -1) {
			return 'wechat'; // 微信环境
		} else if (ua.indexOf('alipay') !== -1) {
			return 'alipay'; // 支付宝环境
		}
		return 'unknown';
	},

	// 支付宝环境监测
	isAlipayBrowser() {
		const ua = navigator.userAgent.toLowerCase()
		const isAlipayClient = ua.indexOf('alipayclient') !== -1
		const isAlipayDefined = ua.indexOf('alipaydefined') !== -1
		return isAlipayClient || isAlipayDefined
	},
	// 支付宝静默授权跳转
	silentAlipayAuth() {
		/*return new Promise((resolve, reject) => {
			console.log(window.ap)
			window.AlipayJSBridge.getAuthCode({
				appId:config.appid_alipay,
				scopes: ['auth_base'], // 静默授权
				
			},(result)=>{
				console.log(result)
				resolve(result)
			});
		});*/
		
		const currentUrl = window.location.href.split('#')[0]
		
		const redirectUri = encodeURIComponent(currentUrl)
		
		window.location.href = `https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${
	    config.appid_alipay
	  }&scope=auth_base&redirect_uri=${redirectUri}&state=SILENT_LOGIN`
	},

	// 增强版微信环境检测
	isWechatBrowser() {
		const ua = navigator.userAgent.toLowerCase()
		const isMicroMessenger = ua.indexOf('micromessenger') !== -1
		const isWechatDevTools = ua.indexOf('wechatdevtools') !== -1
		const isWorkWechat = ua.indexOf('wxwork') !== -1
		return (isMicroMessenger && !isWorkWechat) || isWechatDevTools
	},
	// 微信静默授权跳转
	silentWechatAuth() {
		const currentUrl = window.location.href.split('#')[0]
		const redirectUri = encodeURIComponent(currentUrl)
		window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
      config.appid
    }&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=wx_auth#wechat_redirect`
	}
}